﻿namespace CN2P.Web.Controllers.Api
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    using CN2P.ServiceModel;
    using CN2P.Web.Db;

    public class CartApiController : BaseApiController
    {
        private static readonly Dictionary<string, CartModel> Carts = new Dictionary<string, CartModel>();
        private static readonly object Sync = new object();

        [AcceptVerbs("GET")]
        public CartModel Get(string userId)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                CartModel cart;
                if (Carts.TryGetValue(decodedUserId, out cart))
                {
                    return cart;
                }

                return new CartModel
                {
                    UserId = decodedUserId
                };
            }
        }

        [AcceptVerbs("POST")]
        public HttpResponseMessage Post(string userId, CartModel model)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                model.UserId = decodedUserId;
                Carts[decodedUserId] = model;
            }

            return Request.CreateResponse(HttpStatusCode.Created);
        }

        [AcceptVerbs("DELETE")]
        public HttpResponseMessage DeleteAll()
        {
            lock (Sync)
            {
                Carts.Clear();
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [AcceptVerbs("DELETE")]
        public HttpResponseMessage Delete(string userId)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                if (Carts.ContainsKey(decodedUserId))
                {
                    Carts.Remove(decodedUserId);
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [AcceptVerbs("POST")]
        public HttpResponseMessage PostItem(string userId, CartItemModel model)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                CartModel cart;
                if (!Carts.TryGetValue(decodedUserId, out cart))
                {
                    cart = new CartModel { UserId = decodedUserId };
                    Carts[decodedUserId] = cart;
                }

                var cartItem = cart.Items.FirstOrDefault(item => item.ProdId == model.ProdId);
                if (cartItem == null)
                {
                    cart.Items.Add(model);
                }
                else
                {
                    cartItem.Quantity += model.Quantity;
                }
            }

            return Request.CreateResponse(HttpStatusCode.Created);
        }

        [AcceptVerbs("PUT")]
        public HttpResponseMessage PutItem(string userId, CartItemModel model)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                CartModel cart;
                if (!Carts.TryGetValue(decodedUserId, out cart))
                {
                    cart = new CartModel { UserId = decodedUserId };
                    Carts[decodedUserId] = cart;
                }

                var cartItem = cart.Items.FirstOrDefault(item => item.ProdId == model.ProdId);
                if (cartItem == null)
                {
                    cart.Items.Add(model);
                }
                else
                {
                    cartItem.Quantity = model.Quantity;
                }
            }

            return Request.CreateResponse(HttpStatusCode.Created);
        }

        [AcceptVerbs("DELETE")]
        public HttpResponseMessage DeleteItem(string userId, string prodId)
        {
            var decodedUserId = this.DecodeUserId(userId);
            lock (Sync)
            {
                CartModel cart;
                if (Carts.TryGetValue(decodedUserId, out cart))
                {
                    var cartItem = cart.Items.FirstOrDefault(item => item.ProdId == prodId);
                    if (cartItem != null)
                    {
                        cart.Items.Remove(cartItem);
                    }
                }
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [AcceptVerbs("POST")]
        public HttpResponseMessage Checkout(string userId)
        {
            var decodedUserId = this.DecodeUserId(userId);
            string orderId = "";
            lock (Sync)
            {
                CartModel cart;
                if (Carts.TryGetValue(decodedUserId, out cart))
                {
                    Carts.Remove(decodedUserId);
                    var orderModel = cart.CreateOrder();
                    var order = Order.From(orderModel);

                    using (var context = new ECommerceDataContext())
                    {
                        context.Orders.InsertOnSubmit(order);
                        context.SubmitChanges();
                        orderId = order.Id;
                    }
                }
            }

            return Request.CreateResponse(HttpStatusCode.Created);

            //if (!string.IsNullOrWhiteSpace(orderId))
            //{
            //    response.Headers.Location = new Uri(string.Format("{0}api/orders/{1}/reviews/{2}", OrdersUri, userId, orderId));
            //}
            //return response;
        }
    }
}
